import 'dart:io';

import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/entities/offline_package_entity.dart';
import 'package:flutter_rtk/utils/zip_utils.dart';
import 'package:path_provider/path_provider.dart';

class H5DownloadUtils {
  static downloadH5({required String business, required String applyType}) async {
    // EasyLoading.showInfo("下载H5压缩包中...");
    var directory = await getApplicationDocumentsDirectory();
    OfflinePackageEntity latestPackage = await AppApi.fetchLatestOfflinePackage(packageType: 2, applyType: applyType);
    try {
      latestPackage = await AppApi.fetchLatestOfflinePackage(packageType: 2, applyType: applyType);
    } catch (e) {
      // EasyLoading.dismiss();
      // showToast("获取最新包失败！$e");
      return;
    }
    if (latestPackage.id <= 0) {
      // EasyLoading.showInfo("获取离线包为空");
      return;
    }
    // 下载数据
    await AppApi.downloadFile(
      url: latestPackage.packagePath,
      savePath: "${directory.path}/$business.zip",
      onReceiveProgress: (double p) {
        if (p >= 1) {
          // EasyLoading.showInfo("H5压缩包下载完成，开始加载信息数据...");
        } else {
          // EasyLoading.showProgress(p);
        }
      },
    );
    // 解压数据
    String result = ZipUtils.unZip(zipPath: "${directory.path}/$business.zip", outputPath: "${directory.path}/html/$business");
    if (result.isNotEmpty) {
      // EasyLoading.showError(result);
      return;
    }
    // EasyLoading.showSuccess("新数据加载成功!");
    File("${directory.path}/$business.zip").deleteSync();
    return "${directory.path}/html/$business/index.html?isLocal=1";
  }
}
